USE Core
GO
IF OBJECT_ID('fGetCharPos') IS NOT NULL
BEGIN
    DROP FUNCTION fGetCharPos
    IF OBJECT_ID('fGetCharPos') IS NOT NULL
        PRINT '<<< FAILED DROPPING FUNCTION fGetCharPos >>>'
    ELSE
        PRINT '<<< DROPPED FUNCTION fGetCharPos >>>'
END
GO
CREATE FUNCTION dbo.fGetCharPos
    (
        @str        varchar(255)
    ,   @srchstr    varchar(255)
    ,   @iterations int
 )
-- Description: based on basGetCharPos()
-- Developer: rasx

RETURNS int
AS
BEGIN
    DECLARE
        @inInt  int
    ,   @outInt int
    ,   @loop   int
    ,   @doLoop bit
    ,   @pos    int

    SELECT @doLoop = 1
    SELECT @inInt = 1
    SELECT @outInt = 0

    IF @iterations = 0
    BEGIN
        WHILE @doLoop = 1
        BEGIN
            SELECT @outInt = CHARINDEX(@srchstr,@str,@inInt)
            IF @outInt > 0
            BEGIN
                SELECT @inInt = @outInt + 1
            END
            ELSE
            BEGIN
                SELECT @doLoop = 0
                BREAK
            END
        END
    END

    SELECT @loop = 0
    IF @iterations > 0
    BEGIN
        WHILE @loop < @iterations
        BEGIN
            SELECT @outInt = CHARINDEX(@srchstr,@str,@inInt)
            IF @outInt > 0
            BEGIN
                SELECT @inInt = @outInt + 1
            END
            ELSE
            BEGIN
                BREAK
            END
            SELECT @loop = @loop + 1
        END
    END
    SET @pos = @inInt - 1

RETURN @pos
END
GO
GRANT EXECUTE ON fGetCharPos TO public
GO
IF OBJECT_ID('fGetCharPos') IS NOT NULL
    PRINT '<<< CREATED FUNCTION fGetCharPos >>>'
ELSE
    PRINT '<<< FAILED CREATING FUNCTION fGetCharPos >>>'
GO
